package com.net.xpay.partner.controller.s;


import com.google.common.base.Strings;
import com.net.common.exception.BusinessException;
import com.net.common.util.NetUtil;
import com.net.xpay.common.domain.SafePayBookPreApplyRecord;
import com.net.xpay.common.manager.SafePayBookPreApplyRecordManager;
import com.net.xpay.core.constant.PoseidonErrorCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * 2020/6/28 09:46

 */
@Controller
@Slf4j
@RequestMapping("/s")
@Api(tags = "公共/预申请开通安全发记账本", description = "公共 预申请开通安全发记账本 net")
public class ShortLinkController {


    @Autowired
    private SafePayBookPreApplyRecordManager safePayBookPreApplyRecordManager;


    /**
     * 跳转到支付宝灵峰平台开通记账本页面
     */
    @ApiOperation(value = "跳转到支付宝灵峰平台开通记账本页面")
    @GetMapping("/a/{token}")
    public void goPreAuthPage(HttpServletRequest request, HttpServletResponse response, @PathVariable("token") String token) {
        try {
            log.info("goPreAuthPage token={}|ip={}", token, NetUtil.getRequestRealIp(request));
            if (Strings.isNullOrEmpty(token)) {
                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "无效的链接");
            }
            SafePayBookPreApplyRecord record = safePayBookPreApplyRecordManager.getByToken(token);
            if (record == null) {
                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "链接已失效");
            }

            if (record.getDeadline().isBefore(LocalDateTime.now())) {
                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "链接已过期");
            }

            response.setHeader("Content-Type","text/html; charset=utf-8");
            response.getWriter().println("<!DOCTYPE html>\n" +
                    "<html lang=\"\">\n" +
                    "  <head>\n" +
                    "    <meta charset=\"utf-8\">\n" +
                    "  </head>\n" +
                    "  <body>\n" +
                    "      <script>\n" +
                    "          window.location.href = '"  + record.getApplyUrl()  +  "';\n" +
                    "      </script>\n" +
                    "  </body>\n" +
                    "</html>\n");
            response.flushBuffer();
        } catch (Exception e) {
            log.error("goPreAuthPage error token={}", token, e);
        }
    }



}
